package com.library.web.sys_login.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.library.annotation.Auth;
import com.library.jwt.JwtUtils;
import com.library.utils.ResultUtils;
import com.library.utils.ResultVo;
import com.library.web.sys_login.pojo.LoginParm;
import com.library.web.sys_login.pojo.LoginResult;
import com.library.web.sys_login.pojo.UserInfo;
import com.library.web.sys_menu.pojo.MakeTree;
import com.library.web.sys_menu.pojo.RouterVO;
import com.library.web.sys_menu.pojo.SysMenu;
import com.library.web.sys_menu.service.SysMenuService;
import com.library.web.sys_reader.pojo.SysReader;
import com.library.web.sys_reader.service.SysReaderService;
import com.library.web.sys_user.pojo.SysUser;
import com.library.web.sys_user.service.SysUserService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/system")
public class LoginController {
    @Autowired
    private SysReaderService sysReaderService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SysMenuService sysMenuService;

    //登录
    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginParm parm) {
        if (StringUtils.isEmpty(parm.getUsername()) || StringUtils.isEmpty(parm.getPassword()) || StringUtils.isEmpty(parm.getUserType())) {
            return ResultUtils.error("用户名、密码或用户类型不能为空!");
        }
        if (parm.getUserType().equals("0")) { //0 ：读者
            QueryWrapper<SysReader> query = new QueryWrapper<>();
            query.lambda().eq(SysReader::getUsername, parm.getUsername())
                    .eq(SysReader::getPassword, DigestUtils.md5DigestAsHex(parm.getPassword().getBytes()));
            SysReader one = sysReaderService.getOne(query);
            if (one == null) {
                return ResultUtils.error("检查您的用户身份以及用户名和密码是否正确!");
            }
            //返回数据给前端
            LoginResult result = new LoginResult();
            result.setUserId(one.getReaderId());
            //设置token
            result.setToken(jwtUtils.generateToken(one.getUsername(), parm.getUserType()));
            return ResultUtils.success("登录成功", result);
        } else if (parm.getUserType().equals("1")) { // 1: 系统用户
            QueryWrapper<SysUser> query = new QueryWrapper<>();
            String s = DigestUtils.md5DigestAsHex(parm.getPassword().getBytes());
            query.lambda().eq(SysUser::getUsername, parm.getUsername())
                    .eq(SysUser::getPassword,
                            DigestUtils.md5DigestAsHex(parm.getPassword().getBytes()));
            SysUser one = sysUserService.getOne(query);
            if (one == null) {
                return ResultUtils.error("检查您的用户身份以及用户名和密码是否正确!");
            }
            LoginResult result = new LoginResult();
            result.setUserId(one.getUserId());
            result.setToken(jwtUtils.generateToken(one.getUsername(), parm.getUserType()));
            return ResultUtils.success("登录成功", result);
        } else {
            return ResultUtils.error("用户类型不存在!");
        }
    }

    //获取用户权限字段
    @GetMapping("/getInfo")
    public ResultVo getInfo(Long userId, HttpServletRequest request) {
        //从请求的头部获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            return ResultUtils.error("token过期", 600);
        }
        //从token里面解析用户的类型
        Claims claims = jwtUtils.getClaimsFromToken(token);
        Object userType = claims.get("userType");
        //定义用户信息类
        UserInfo userInfo = new UserInfo();
        if (userType.equals("0")) { //读者
            //根据id查询读者信息
            SysReader reader = sysReaderService.getById(userId);
            if (reader != null) {
                userInfo.setIntroduction(reader.getLearnNum());
                userInfo.setName(reader.getLearnNum());
                userInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
                //权限字段查询与设置
                List<SysMenu> menuList = sysMenuService.getReaderMenuByUserId(userId);
                List<String> collect = menuList.stream().filter(item -> item != null
                        && item.getCode() != null).map(item ->
                        item.getCode()).collect(Collectors.toList());
                if (collect.size() == 0) {
                    return ResultUtils.error("暂无登录权限，请联系管理员!");
                }
                //转成数组
                String[] strings = collect.toArray(new String[collect.size()]);
                userInfo.setRoles(strings);
                return ResultUtils.success("查询成功", userInfo);
            } else {
    return  ResultUtils.error("登录已过期,请重新登录!");
            }
        } else if (userType.equals("1")) { //管理员
            SysUser user = sysUserService.getById(userId);
            if (user != null) {
                userInfo.setIntroduction(user.getNickName());
                userInfo.setName(user.getNickName());
                userInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
                //权限字段查询与设置
                List<SysMenu> menuList = sysMenuService.getMenuByUserId(userId);
                List<String> collect = menuList.stream().filter(item -> item != null
                        && item.getCode() != null).map(item ->
                        item.getCode()).collect(Collectors.toList());
                if (collect.size() == 0) {
                    return ResultUtils.error("暂无登录权限，请联系管理员!");
                }
                //转成数组
                String[] strings = collect.toArray(new String[collect.size()]);
                userInfo.setRoles(strings);
                return ResultUtils.success("查询成功", userInfo);
            } else {
                return ResultUtils.error("登录已过期,请重新登录!", userInfo);
            }
        } else {
            return ResultUtils.success("用户类型不存在", userInfo);
        }
    }

    //查询菜单
    @GetMapping("/getMenuList")
    public ResultVo getMenuList(HttpServletRequest request) {
        //获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            return ResultUtils.error("token过期", 600);
        }
        //获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        //获取用户类型
        Claims claims = jwtUtils.getClaimsFromToken(token);
        Object userType = claims.get("userType");
        if (userType.equals("0")) { //读者
            //获取用户信息
            SysReader reader = sysReaderService.loadByUsername(username);
            //获取权限信息
            List<SysMenu> menuList = sysMenuService.getReaderMenuByUserId(reader.getReaderId());
            List<SysMenu> collect = menuList.stream().filter(item -> item != null && !item.getType().equals("2")).collect(Collectors.toList());
            if (collect.size() == 0) {
                return ResultUtils.error("暂无登录权限，请联系管理员!");
            }
            //组装路由格式的数据
            List<RouterVO> routerVOS = MakeTree.makeRouter(collect, 0L);
            return ResultUtils.success("查询成功", routerVOS);
        } else if (userType.equals("1")) { // 管理员
            //获取用户信息
            SysUser reader = sysUserService.loadByUsername(username);
            //获取权限信息
            List<SysMenu> menuList = sysMenuService.getMenuByUserId(reader.getUserId());
            List<SysMenu> collect = menuList.stream().filter(item -> item != null && !item.getType().equals("2")).collect(Collectors.toList());
            if (collect.size() == 0) {
                return ResultUtils.error("暂无登录权限，请联系管理员!");
            }
            List<RouterVO> routerVOS = MakeTree.makeRouter(collect, 0L);
            return ResultUtils.success("查询成功", routerVOS);
        } else {
            return ResultUtils.error("用户类型不存在!");
        }
    }
}
